# coding:utf8
'''
日报
'''

import email
import sys
import smtplib
import os,getopt
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart


class MyEmail:
    def __init__(self):
        self.user = None
        self.passwd = None
        self.to_list = []
        self.cc_list = []
        self.tag = None
        self.doc = None

    def send(self,subject,text_file_path):
        '''
        发送邮件
        '''
        try:
            server = smtplib.SMTP_SSL("smtp.exmail.qq.com", port=465)
            server.login(self.user, self.passwd)
            #server.sendmail("<%s>" % self.user, self.to_list, self.get_attach())

            _user = self.user
            _pwd = self.passwd
            _to = self.user

            file_object = open(text_file_path)

            all_the_text = file_object.read()

            try:
                msg = MIMEText(all_the_text, "base64", "utf-8")
                msg["Subject"] = subject
                msg["From"] = _user
                msg["To"] = _to
                server.sendmail(_user, _to, msg.as_string())
                print "send email successful"
            finally:
                server.close()
                file_object.close()

        except Exception, e:
            print "send email failed %s" % e

    def get_attach(self):
        '''
        构造邮件内容
        '''
        attach = MIMEMultipart()
        if self.tag is not None:
            # 主题,最上面的一行
            attach["Subject"] = self.tag
        if self.user is not None:
            # 显示在发件人
            attach["From"] = "发件人姓名，可以自定义<%s>" % self.user
        if self.to_list:
            # 收件人列表
            attach["To"] = ";".join(self.to_list)
        if self.cc_list:
            # 抄送列表
            attach["Cc"] = ";".join(self.cc_list)
        if self.doc:
            # 估计任何文件都可以用base64，比如rar等
            # 文件名汉字用gbk编码代替
            name = os.path.basename(self.doc).encode("gbk")
            f = open(self.doc, "rb")
            doc = MIMEText(f.read(), "base64", "gb2312")
            doc["Content-Type"] = 'application/octet-stream'
            doc["Content-Disposition"] = 'attachment; filename="' + name + '"'
            attach.attach(doc)
            f.close()
        return attach.as_string()




def main(argv):

   subject=''
   text_file_path=''
   attach_path = ''
   try:
      opts, args = getopt.getopt(argv,"hs:t:",["s=","t="])
   except getopt.GetoptError:
      print ' -s <subject> -o <text> -a <attach path>'
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print ' -s <subject> -o <text> -a <attach path>'
         sys.exit()
      elif opt in ("-s"):
          subject = arg
      elif opt in ("-t"):
          text_file_path = arg

   my = MyEmail()

   my.user = "jie.zhang@dmall.com"
   my.passwd = "Zhangjie@123456"
   #my.tag = "日报"
   #my.doc = attach_path

   my.send(subject, text_file_path)

if __name__ == "__main__":
   main(sys.argv[1:])